package br.com.winesys.geta.databinding.component.editor;

import java.awt.Toolkit;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class LimitedTextArea extends JTextArea {

	public LimitedTextArea() {
		setBorder(BorderFactory.createLoweredBevelBorder());
		setLineWrap(true);
		setWrapStyleWord(true);
	}

	public LimitedTextArea(int limit) {
		this();
		this.setLimit(limit);
	}

	public void setLimit(int limit) {
		if (limit > 0) {
			this.setDocument(new LimitedDocument(limit));
		} else {
			this.setDocument(new PlainDocument());
		}
	}

	private class LimitedDocument extends PlainDocument {

		private int limit = 0;

		public LimitedDocument(int limit) {
			this.limit = limit;
			setDocumentFilter(new DocumentFilter() {

				@Override
				public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
					if ((fb.getDocument().getLength() + str.length()) <= LimitedDocument.this.limit) {
						super.insertString(fb, offs, str, a);
					} else {
						Toolkit.getDefaultToolkit().beep();
					}
				}

				@Override
				public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
					if ((fb.getDocument().getLength() + str.length() - length) <= LimitedDocument.this.limit) {
						super.replace(fb, offs, length, str, a);
					} else {
						Toolkit.getDefaultToolkit().beep();
					}
				}
			});
		}
	}
}
